const { expect } = require("chai")
const { ethers, deployments } = require("hardhat")

describe("Wallet 测试", function () {
    let walletContract
    let deployer
    let user1
    let walletDeployment

    beforeEach(async function () {
        // 1. 部署合约
        await deployments.fixture(["Wallet"])
        // 2. 获取签名者（不依赖namedAccounts的备用方案）
        const signers = await ethers.getSigners()
        deployer = signers[0].address // 直接使用第一个签名者作为部署者
        user1 = signers[1]
        // 3. 获取合约实例
        walletDeployment = await deployments.get("Wallet")

        walletContract = await ethers.getContractAt(
            "Wallet",
            walletDeployment.address
        )
        console.log("部署者地址:", deployer) // 现在应该显示正确地址
        console.log("合约地址:", walletDeployment.address)
    })
    //owner
    it("owner is deployer", async function () {
        const contractOwner = await walletContract.i_owner()
        expect(contractOwner).to.equal(deployer)
    })
    // 测试存款功能
    //run npx hardhat test --grep "senTransaction"
    it("senTransaction", async function () {
        const depositAmount = ethers.parseEther("1")
        // 从user1向钱包存款1 ETH
        const tx = await user1.sendTransaction({
            to: walletDeployment.address,
            value: depositAmount,
        })
        // 等待交易确认（重要！确保交易已上链）
        await tx.wait()
        // 验证余额
        const balance = await walletContract.getbalance()
        console.log("====", balance)
        expect(balance).to.equal(depositAmount)
    })
    //测试 管理员发送以太币
    it("withDraw", async function () {
        const depositAmount = ethers.parseEther("0.1")
        // 从user1向钱包存款1 ETH
        const tx = await user1.sendTransaction({
            to: walletDeployment.address,
            value: depositAmount,
        })
        // 等待交易确认（重要！确保交易已上链）
        await tx.wait()

        //执行取现
        const withdrawAmount = ethers.parseEther("0.05")
        const tx1 = await walletContract.withDraw(user1.address, withdrawAmount)
        await tx1.wait()
        const balanceAfter = await walletContract.getbalance()
        //合约余额 -0.5
        expect(balanceAfter).to.equal(withdrawAmount)

        // 2. 收款地址应该收到0.5 ETH
        const receiverBalanceAfter = await walletContract.getAddressBalance(
            user1.address
        )
        //user1初始账户
        const receiverBalanceBefore = await ethers.provider.getBalance(
            user1.address
        )
        expect(receiverBalanceAfter).to.be.lt(
            receiverBalanceBefore + withdrawAmount
        )
    })
})
